using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using FireStarterModeller.BO;
using Habanero.Base.Exceptions;
using Habanero.BO;

namespace FireStarterModeller.Logic.Commands
{
    public class DeleteAssemblyCommand : ICommand
    {
        private readonly DMAssembly _assembly;
        private DMSolution _solution;

        public DeleteAssemblyCommand(DMAssembly assembly)
        {
            _assembly = assembly;
        }

        public void Apply()
        {
            _solution = _assembly.Solution;
            _assembly.MarkForDelete();
            try
            {
                _assembly.Save();
            } catch (Exception)
            {
                _assembly.CancelEdits();
                throw;
            }

        }
        public void Revert() {
            PropertyInfo isDeletedProperty = typeof(BOStatus).GetProperty("IsDeleted", BindingFlags.Public | BindingFlags.Instance);
            isDeletedProperty.SetValue(_assembly.Status, false, null);
            PropertyInfo isDirtyProperty = typeof(BOStatus).GetProperty("IsDirty", BindingFlags.Public | BindingFlags.Instance);
            isDirtyProperty.SetValue(_assembly.Status, true, null);
            PropertyInfo isNewProperty = typeof(BOStatus).GetProperty("IsNew", BindingFlags.Public | BindingFlags.Instance);
            isNewProperty.SetValue(_assembly.Status, true, null);

            _solution.Assemblies.Add(_assembly);
            try
            {
                _assembly.Save();
            }
            catch (Exception)
            {
                _solution.Assemblies.Remove(_assembly);
                throw;
            } 
        }
    }
}
